﻿using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using CsvHelper;
using CsvHelper.Configuration;
using SDCloudSolution.SDCloud.Web.Infrastructure.Interfaces;
using SDCloudSolution.SDCloud.Web.Models.ResultData;

namespace SDCloudSolution.SDCloud.Web.Infrastructure
{
    public class ModelResultsCsvConverter : IModelResultsConverter
    {
        public Task<Stream> ConvertToContentAsync(ModelResultDataViewModel results, CultureInfo cultureInfo)
        {
            return Task.Run<Stream>(() =>
            {
                var stream = new MemoryStream();
                var writer = new StreamWriter(stream);

                var usedCultureInfo = cultureInfo ?? CultureInfo.InvariantCulture;
                var settings = new CsvConfiguration
                {
                    CultureInfo = usedCultureInfo,
                    Delimiter = usedCultureInfo.TextInfo.ListSeparator
                };
                var csv = new CsvWriter(writer, settings);

                csv.WriteField("Time");
                foreach (var column in results.Columns)
                {
                    csv.WriteField(column.DisplayName);
                }
                csv.NextRecord();

                foreach (var timeFrame in results.Frames)
                {
                    csv.WriteField(timeFrame.Time);
                    foreach (var column in results.Columns)
                    {
                        csv.WriteField(timeFrame.Values[column.Id]);
                    }
                    csv.NextRecord();
                    writer.Flush();
                }

                stream.Seek(0, SeekOrigin.Begin);
                return stream;
            });
        }
    }
}